"""
Case Type   : 发布订阅
Case Name   : 检查gs_probackup备份发布订阅时是否存在常驻明文密码
Create At   : 2023/10/17
Owner       : songjing20
Description :
    1.在两个集群创建模式、表空间和表
    2.发布端打开增量备份开关
    3.创建发布订阅
    4.全量备份发布端
    5.查询进程中是否有密码相关
    6.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.不存在密码
    6.成功
History     :
"""

import os
import time
import unittest

from yat.test import macro
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 > Primary_SH.get_node_num(), '非1+2以上环境不执行')
class Pubsubclass(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.pri_userdb_pub = Node(node='PrimaryDbUser')
        self.pri_userdb_sub = Node(node='remote1_PrimaryDbUser')
        self.constant = Constant()
        self.commsh_pub = CommonSH('PrimaryDbUser')
        self.commsh_pub_std = [CommonSH('Standby1DbUser'),
                               CommonSH('Standby2DbUser')]
        self.commsh_sub = CommonSH('remote1_PrimaryDbUser')
        self.com_pub = Common()
        self.com_sub = Common('remote1_PrimaryDbUser')
        self.schema = 's_pubsub_0214'
        self.tablespace = 'tbs_pubsub_0214'
        self.tb_name1 = 't_pubsub_0214_1'
        self.tb_name2 = 't_pubsub_0214_2'
        self.subname = "sub_pubsub_0214"
        self.pubname = "pub_pubsub_0214"
        self.path1 = os.path.join(
            os.path.dirname(macro.DB_INSTANCE_PATH), 'tablespace_0214')
        self.path2 = os.path.join(
            os.path.dirname(macro.DB_INSTANCE_PATH_REMOTE1), 'tablespace_0214')
        self.basebackup = os.path.join(
            os.path.dirname(macro.DB_INSTANCE_PATH), 'basebackup')
        self.parent_path_pub = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.port = str(int(self.pri_userdb_pub.db_port) + 1)
        self.wal_level = self.com_pub.show_param("wal_level")
        self.enable_cbm_tracking = self.com_pub.show_param(
            "enable_cbm_tracking")
        self.user_param_pub = f'-U {self.pri_userdb_pub.db_user} ' \
                              f'-W {self.pri_userdb_pub.db_password}'
        self.user_param_sub = f'-U {self.pri_userdb_sub.db_user} ' \
                              f'-W {self.pri_userdb_sub.db_password}'
        text = '-----查询集群状态,配置白名单,发布端设置wal_level=logical-----'
        self.log.info(text)
        self.log.info('-----发布端状态-----')
        status = self.commsh_pub.get_db_cluster_status('detail')
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        self.log.info('-----订阅端状态-----')
        status = self.commsh_sub.get_db_cluster_status(
            'detail', env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host  replication  {self.pri_userdb_sub.db_user}  '
            f'{self.pri_userdb_sub.db_host}/32  sha256')
        self.log.info(guc_res)
        self.assertTrue(guc_res, f'发布端配置白名单失败:{text}')
        if 'logical' != self.wal_level:
            result = self.commsh_pub.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG, 'wal_level=logical')
            self.assertTrue(result, f'设置wal_level失败:{text}')
            restart_res = self.commsh_pub.restart_db_cluster()
            self.assertTrue(restart_res, f'重启数据库失败:{text}')
        guc_res = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host  replication  {self.pri_userdb_pub.db_user}  '
            f'{self.pri_userdb_pub.db_host}/32  sha256',
            macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res)
        self.assertTrue(guc_res, f'订阅端配置白名单失败:{text}')

    def test_pub_sub(self):
        text1 = "-----step1:在两个集群创建模式、表空间和表;expect:成功-----"
        self.log.info(text1)
        sql = """drop schema if exists {0} cascade;
        create schema {0};
        drop tablespace if exists {1};
        create tablespace {1} location '{2}';
        drop table if exists {0}.{3};
        drop table if exists {4};
        create table {0}.{3}(id1 int primary key, id2 int, id3 int);
        create table {4}(id int primary key constraint id_nn not null,
        use_filename varchar2(20),filename varchar2(255),
        text varchar2(2000)) tablespace {1} partition by range(id)
        ( partition p1 values less than(30),
          partition P2 values less than(60),
          partition P3 values less than(90),
          partition P4 values less than(MAXVALUE));"""
        pub_res = self.commsh_pub.execut_db_sql(
            sql.format(self.schema, self.tablespace, self.path1, self.tb_name1,
                       self.tb_name2),
            sql_type=self.user_param_pub)
        self.log.info(pub_res)
        self.assertIn(self.constant.CREATE_SCHEMA_SUCCESS_MSG, pub_res,
                      f"执行失败:{text1}")
        self.assertIn(self.constant.TABLESPCE_CREATE_SUCCESS, pub_res,
                      f"执行失败:{text1}")
        self.assertEqual(pub_res.count(self.constant.TABLE_CREATE_SUCCESS),
                         5, f"执行失败:{text1}")
        sub_res = self.commsh_sub.execut_db_sql(
            sql.format(self.schema, self.tablespace, self.path2, self.tb_name1,
                       self.tb_name2),
            self.user_param_sub,
            env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_res)
        self.assertIn(self.constant.CREATE_SCHEMA_SUCCESS_MSG, sub_res,
                      f"执行失败:{text1}")
        self.assertIn(self.constant.TABLESPCE_CREATE_SUCCESS, sub_res,
                      f"执行失败:{text1}")
        self.assertEqual(sub_res.count(self.constant.TABLE_CREATE_SUCCESS),
                         5, f"执行失败:{text1}")

        text2 = "-----step2:发布端打开增量备份开关;expect:成功-----"
        self.log.info(text2)
        result = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            'enable_cbm_tracking=on')
        self.log.info(result)
        self.assertTrue(result, f"执行失败:{text2}")

        text3 = "-----step3:创建发布订阅;expect:成功-----"
        self.log.info(text3)
        sql_cmd = f"drop publication if exists {self.pubname};" \
                  f"create publication {self.pubname} for table " \
                  f"{self.schema}.{self.tb_name1},{self.tb_name2};"
        pub_result = self.commsh_pub.execut_db_sql(
            sql_cmd, sql_type=self.user_param_pub)
        self.log.info(pub_result)
        self.assertIn(self.constant.create_pub_succ_msg, pub_result,
                      f"执行失败:{text3}")
        result = self.commsh_sub.execute_generate(
            macro.COMMON_PASSWD, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.assertIn(self.constant.create_keycipher_success, result,
                      f"执行失败:{text3}")
        sql_cmd = f"drop subscription if exists {self.subname};" \
                  f"create subscription {self.subname} connection " \
                  f"'host={self.pri_userdb_pub.db_host} " \
                  f"port={self.port} user={self.pri_userdb_pub.db_user} " \
                  f"dbname={self.pri_userdb_pub.db_name} " \
                  f"password={self.pri_userdb_pub.ssh_password}' " \
                  f"publication {self.pubname};"
        sub_result = self.commsh_sub.execut_db_sql(
            sql_cmd, self.user_param_sub, None, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_result)
        self.assertIn(self.constant.create_sub_succ_msg, sub_result,
                      f"执行失败:{text3}")

        text4 = "-----step4:发布端全量备份;expect:成功-----"
        self.log.info(text4)
        check_cmd = f'if [ -d {self.basebackup} ]; then ' \
                    f'rm -rf {self.basebackup}; fi; mkdir {self.basebackup};'
        self.log.info(check_cmd)
        result = self.pri_userdb_pub.sh(check_cmd).result()
        self.log.info(result)
        gs_probackup_init = self.commsh_pub.exec_pro_backup_init(
            self.basebackup)
        self.log.info(gs_probackup_init)
        self.assertTrue(gs_probackup_init, f"执行失败:{text4}")
        gs_probackup_add = self.commsh_pub.exec_pro_back_add(
            self.basebackup, 'instance', dn_path=macro.DB_INSTANCE_PATH)
        self.log.info(gs_probackup_add)
        self.assertTrue(gs_probackup_add, f"执行失败:{text4}")
        gs_probackup = ComThread(self.commsh_pub.exec_pro_backup_backup, args=(
            self.basebackup, 'instance', 'full', self.pri_userdb_pub.db_name,
            f'--backup-pg-replslot -E {self.path1}'))
        gs_probackup.setDaemon(True)
        gs_probackup.start()

        text5 = "-----step5:查询进程中是否有密码相关;expect:不存在密码-----"
        self.log.info(text5)
        time.sleep(1)
        cmd = f"pgrep -a -u {self.pri_userdb_pub.ssh_user} -f ^gs_probackup;"
        self.log.info(cmd)
        res = self.pri_userdb_pub.sh(cmd).result()
        self.log.info(res)
        pid = res.split()[0].strip()
        cmd = f"cd {self.parent_path_pub};gcore -o core {pid};"
        self.log.info(cmd)
        result = self.com_pub.get_sh_result(self.pri_userdb_pub, cmd)
        self.log.info(result)
        cmd = f"cd {self.parent_path_pub};" \
              f"strings core.{pid} > core.log;" \
              f"grep {macro.COMMON_PASSWD} core.log;" \
              f"grep {self.pri_userdb_pub.ssh_password} core.log;" \
              f"rm -f core.{pid} core.log;"
        self.log.info(cmd)
        cmd_res = self.com_pub.get_sh_result(self.pri_userdb_pub, cmd)
        self.log.info(cmd_res)
        self.log.info('-----gs_probackup result-----')
        gs_probackup.join(60)
        gs_probackup_res = gs_probackup.get_result()
        self.log.info(gs_probackup_res)
        self.assertTrue(gs_probackup_res, f"执行失败:{text4}")
        self.assertIn("Saved corefile", result, f"执行失败:{text5}")
        self.assertNotIn(macro.COMMON_PASSWD, cmd_res, f"执行失败:{text5}")
        self.assertNotIn(self.pri_userdb_pub.ssh_password, cmd_res,
                         f"执行失败:{text5}")

    def tearDown(self):
        text = "-----step6:清理环境;expect:成功-----"
        self.log.info(text)
        drop_sub_res = self.commsh_sub.execut_db_sql(
            f"drop subscription if exists {self.subname};",
            self.user_param_sub, None, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(drop_sub_res)
        drop_pub_res = self.commsh_pub.execut_db_sql(
            f"drop publication if exists {self.pubname};",
            sql_type=self.user_param_pub)
        self.log.info(drop_pub_res)
        sql_cmd = f"drop table if exists {self.schema}.{self.tb_name1};" \
                  f"drop table if exists {self.tb_name2};" \
                  f"drop schema if exists {self.schema} cascade;" \
                  f"drop tablespace if exists {self.tablespace};"
        drop_res0 = self.commsh_sub.execut_db_sql(
            sql_cmd, self.user_param_sub, None, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(drop_res0)
        drop_res1 = self.commsh_pub.execut_db_sql(
            sql_cmd, sql_type=self.user_param_pub)
        self.log.info(drop_res1)
        wal_level_res = self.commsh_pub.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'wal_level={self.wal_level}')
        self.log.info(wal_level_res)
        guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'enable_cbm_tracking={self.enable_cbm_tracking}')
        self.log.info(guc_res)
        pub_guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host  replication  {self.pri_userdb_sub.db_user}  '
            f'{self.pri_userdb_sub.db_host}/32')
        self.log.info(pub_guc_res)
        restart_res = self.commsh_pub.restart_db_cluster()
        sub_guc_res = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host  replication  {self.pri_userdb_pub.db_user}  '
            f'{self.pri_userdb_pub.db_host}/32', macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_guc_res)
        cmd = f"rm -rf {self.path1};rm -rf {self.basebackup};"
        self.log.info(cmd)
        sh_result1 = self.pri_userdb_pub.sh(cmd).result()
        self.log.info(sh_result1)
        cmd = f"rm -rf {self.path2};"
        self.log.info(cmd)
        sh_result2 = self.pri_userdb_sub.sh(cmd).result()
        self.log.info(sh_result2)
        self.assertIn(self.constant.drop_sub_succ_msg, drop_sub_res,
                      f'删除订阅失败:{text}')
        self.assertIn(self.constant.drop_pub_succ_msg, drop_pub_res,
                      f'删除发布失败:{text}')
        self.assertEqual(drop_res0.count(self.constant.DROP_TABLE_SUCCESS), 3,
                         f'删除订阅端表失败:{text}')
        self.assertIn(self.constant.DROP_SCHEMA_SUCCESS_MSG, drop_res0,
                      f"删除订阅端模式失败:{text}")
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, drop_res0,
                      f"删除订阅端表空间失败:{text}")
        self.assertEqual(drop_res1.count(self.constant.DROP_TABLE_SUCCESS), 3,
                         f'删除发布端表失败:{text}')
        self.assertIn(self.constant.DROP_SCHEMA_SUCCESS_MSG, drop_res1,
                      f"删除发布端模式失败:{text}")
        self.assertIn(self.constant.TABLESPCE_DROP_SUCCESS, drop_res1,
                      f"删除发布端表空间失败:{text}")
        self.assertTrue(wal_level_res and guc_res, f'执行失败:{text}')
        self.assertTrue(restart_res, f'发布端重启数据库失败:{text}')
        self.assertTrue(pub_guc_res, f'发布端删除白名单失败:{text}')
        self.assertTrue(sub_guc_res, f'订阅端删除白名单失败:{text}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
